<script lang="ts">
	import { page } from '$app/stores';
	import { getValue } from '$utils/get';
	import { formatMoney, transformDisplayToNumber } from '$utils/money';
	import { handleReqMounted } from '@/hooks/handleReq';
	import TableRow from './_com/TableRow.svelte';
	import TableCol from './_com/TableCol.svelte';
	import { PageLoading } from '$components/basic/loading';
	import Divider from '$components/basic/divider/divider.svelte';
	import { writable } from 'svelte/store';
	import { formatDate } from '$utils/date';
	import Button from '@smui/button';
	import { goBack, goto } from '$utils/intercept';
	import { exportDomToImageById, exportPngToPDF } from '$utils/export';
	import { createDialog } from '$components/basic/dialog/dialog';
	import '$lib/css/invoice.scss';

	let detail = writable<Order.InvoiceData>({}); // 详情数据

	const getDetail = (urls: string, defaultValue?: any) => {
		return getValue($detail, urls, defaultValue || '');
	};

	const getPositiveNumber = (val: string | number) => {
		if (!isNaN(Number(val))) {
			if (Number(val) < 0) {
				return 0;
			}
			return Number(val);
		}
		return 0;
	};

	let blankHieght = getPositiveNumber('init'); // 计算空白高度
	let diagonal = 0; // 斜边
	let angle = 0; // 角度
	let sign = ''; // 签名

	const getParams = () =>
		$page.url.search
			.split('?')[1]
			.split('&')
			.reduce((pre, cur) => {
				return { ...pre, [cur.split('=')[0]]: cur.split('=')[1] };
			}, {});
	const params = getParams() as IObject;
	const handle = (res) => {
		console.log(res);
		detail.set(res.data);
		sign = getDetail('basicData.currency');
		blankHieght = getPositiveNumber(650 - ($detail.itemData!.length + 1) * 32);

		console.log(blankHieght);

		const [h, w] = [blankHieght, 868];
		diagonal = Math.sqrt(h ** 2 + w ** 2);
		angle = (Math.atan(w / h) * 180) / Math.PI;
		console.log(diagonal, angle);
	};
	const onChangeUnitPrice = (e: Event, item: Order.ItemData) => {
		const target = e.target as HTMLInputElement;
		const value = String(target.textContent).replace(sign, '').trim();
		if (!isNaN(Number(value))) {
			target.textContent = Number(value).toFixed(2);
			const amount = Number(value) * Number(item.qty);
			item.amount = amount.toFixed(2);

			detail.update((v) => {
				console.log(v);

				const result = v
					.itemData!.map((item: Order.ItemData) => transformDisplayToNumber(item.amount))
					.reduce((a: number, b: number) => a + b, 0)
					.toFixed(2);
				console.log(result);
				v.basicData!.itemAmount = result;

				return v;
			});
		}
	};

	const onChangeShipping = (e: Event) => {
		const target = e.target as HTMLInputElement;
		const value = String(target.textContent).replace(sign, '').trim();
		if (!isNaN(Number(value))) {
			target.textContent = Number(value).toFixed(2);
			$detail.basicData!.shipping = Number(value).toFixed(2);
		}
	};
	const { loading, error } = handleReqMounted(() => '/order/invoice?id=' + params.id, {
		type: 'get',
		handle
	});

	const exportTableForPng = () => {
		createDialog('tip', 'generating pdf, please wait...', () => {
			const dom = document.getElementById('sale-invoice__content');
			// return console.log(dom);

			if (dom) {
				exportDomToImageById(dom, (_, canvas) => {
					const pdfName = `MACNN-SalesOrder${$detail.basicData!.orderno}.pdf`;
					exportPngToPDF(() => [pdfName, canvas as HTMLCanvasElement]);
				});
			}
		});
	};
</script>

<div class="w-full flex-cc">
	<div class="w-1320px max-w-100% min-w-350px flex flex-col items-center py-20px gap-15px">
		<div class="w-full flex justify-between items-center bg-gray-2 h-48px pr-10px">
			<Button class="gap-10px h-full" style="--mdc-theme-primary: #6b7280" on:click={goBack}>
				<span class="material-symbols-outlined"> undo </span>
				<span>Back</span>
			</Button>
			<div class="flex-cc gap-10px h-full">
				<Button
					class="gap-10px"
					style="background-color:#e30000; --mdc-theme-primary: #6b728"
					variant="raised"
					on:click={exportTableForPng}
				>
					<span>Print PDF</span>
				</Button>
			</div>
		</div>

		<PageLoading bind:loading={$loading}>
			<div class="w-940px p-20px" id="sale-invoice__content">
				<div
					class="invoice invoice-wrapper p-15px w-full overflow-hidden box-border border border-solid border-gray-8"
				>
					<div class="invoice-header">
						<TableRow>
							<div class="grid-col-span-24 w-full h-36px line-height-36px flex-cc relative">
								<span class="invoice__title font-size-30px font-600 color-#000"
									>{getDetail('basicData.title')}</span
								>
								<!-- {/* 右上角 两个长方形连在一起的格子，一个日期一个单号，灰色边框 */} -->
								<div class="flex flex-row absolute right-0 top-0 border-collapse line-height-15px">
									<div
										class="h-40px border border-solid border-gray-400 font-size-11px pt-3.5px px-7.5px box-border border-r-0 text-center"
									>
										<span>S/O</span>
										<br />
										<span>#{getDetail('basicData.orderno')}</span>
									</div>
									<div
										class="h-40px border border-solid border-gray-400 font-size-11px pt-3.5px px-7.5px box-border text-center"
									>
										<span>S/O Date</span>
										<br />
										<span>{getDetail('basicData.created_at')}</span>
									</div>
								</div>
							</div>
						</TableRow>
						<TableRow>
							<div class="grid-col-span-24 invoice__tip w-full flex-cc font-size-22px font-400">
								{getDetail('basicData.saler')}
							</div>
						</TableRow>
						<TableRow>
							<div class="invoice__tip grid-col-span-24 w-full flex-cc font-size-18px font-200">
								{getDetail('basicData.salerAddress')}
							</div>
						</TableRow>
						<Divider style="--mdc-theme-primary: #000"></Divider>
						<TableRow>
							<TableCol span={12}>
								<span class="invoice__content__title">Sold To</span>
							</TableCol>
							<TableCol span={12}>
								<span class="invoice__content__title">Ship To</span>
							</TableCol>
						</TableRow>
						<TableRow class="mt-2px">
							<TableCol class="invoice__table__border invoice__table__item" span={12}>
								<div>Vendor:{getDetail('basicData.customer')}</div>
								<div>{getDetail('soldData:0.name') || '----'}</div>
								<div>Company:{getDetail('soldData:0.company')}</div>
								<div>Phone:{getDetail('soldData:0.tel')}</div>
								<div>Tax:{getDetail('soldData:0.tax')}</div>
							</TableCol>
							<TableCol
								class="invoice__table__border invoice__table__item overflow-hidden"
								span={12}
							>
								<div>Company:{getDetail('shipData.companyName')}</div>
								<div>
									Address:
									{getDetail('shipData.aDetail')
										? `${getDetail('shipData.aDetail')},${getDetail('shipData.aCity')},${getDetail('shipData.aProvince')},${getDetail('shipData.aCountry')}`
										: ''}
								</div>
								<div>
									Contact:{getDetail('shipData.fName')}
									{getDetail('shipData.lName')}
								</div>
								<div>Postcode:{getDetail('shipData.postcode')}</div>
							</TableCol>
						</TableRow>
						<TableRow class="mt-15px">
							<TableCol class="invoice__table__border invoice__table__item" span={6}
								>Terms: Wire</TableCol
							>
							<TableCol class="invoice__table__border invoice__table__item" span={6}>
								ShipDate:{getDetail('basicData.shipDate')}
							</TableCol>
							<TableCol class="invoice__table__border invoice__table__item" span={6}
								>Print Time:{formatDate('MM/DD/YY', new Date())}</TableCol
							>
							<TableCol
								class="invoice__table__border invoice__table__item "
								style="font-size:11px; align-content: center;"
								span={6}
							>
								{getDetail('basicData.shipway')}
							</TableCol>
						</TableRow>
						<TableRow class="mt-15px">
							<TableCol
								class="invoice__table__border invoice__table__item font-bold text-center"
								span={2}
							>
								Line
							</TableCol>
							<TableCol
								class="invoice__table__border invoice__table__item font-bold text-center"
								span={3}
							>
								Item No.
							</TableCol>
							<TableCol class="invoice__table__border invoice__table__item font-bold" span={10}>
								Description
							</TableCol>
							<TableCol
								class="invoice__table__border invoice__table__item font-bold text-center"
								span={3}
							>
								Unit Price
							</TableCol>
							<TableCol
								class="invoice__table__border invoice__table__item font-bold text-center"
								span={3}
							>
								Qty
							</TableCol>
							<TableCol
								class="invoice__table__border invoice__table__item font-bold text-center"
								span={3}
							>
								Amount
							</TableCol>
						</TableRow>
						{#each $detail.itemData || [] as item, index}
							<TableRow class="invoice__table__brother">
								<TableCol class="invoice__table__border invoice__table__item text-center" span={2}>
									{index + 1}
								</TableCol>
								<TableCol class="invoice__table__border invoice__table__item text-center" span={3}>
									{item.code + '-' + (item.dash ? item.dash : '--')}
								</TableCol>
								<TableCol class="invoice__table__border invoice__table__item " span={10}>
									{item.description}
								</TableCol>
								<TableCol class="invoice__table__border invoice__table__item text-center" span={3}>
									<div>
										{sign}{' '}
										<span
											class="outline-none"
											contenteditable
											on:blur={(e) => onChangeUnitPrice(e, item)}
										>
											{item.unitprice}
										</span>
									</div>
								</TableCol>
								<TableCol class="invoice__table__border invoice__table__item text-center" span={3}>
									{item.qty}
								</TableCol>
								<TableCol class="invoice__table__border invoice__table__item text-center" span={3}>
									{sign}
									{item.amount}
								</TableCol>
							</TableRow>
						{/each}

						{#if blankHieght}
							<TableRow class="invoice__table__brother">
								<TableCol
									class="invoice__table__border invoice__table__item font-size-80px font-bold color-gray-3 relative overflow-clip"
									style={`height: ${blankHieght}px`}
									span={24}
								>
									<div
										style={`width: 1px; height: ${diagonal}px; transform: rotate(-${angle}deg)`}
										class="z-1 absolute top-0 left-0 bg-gray-2 transform-origin-top-left"
									></div>
									<div
										style={`width: 1px; height: ${diagonal}px; transform: rotate(${angle}deg)`}
										class="z-1 absolute top-0 right-0 bg-gray-2 transform-origin-top-right"
									></div>
									<span class="z-2 block absolute top-50% left-50% -translate-50%">NO MORE</span>
								</TableCol>
							</TableRow>
						{/if}

						<TableRow class="mt-15px">
							<TableCol class="invoice__table__border invoice__table__item font-bold" span={7}>
								Comments:
							</TableCol>
							<TableCol class="invoice__table__border invoice__table__item" span={5}>
								<div class="font-bold">Package Info</div>
								<div>Quantites: {getDetail('basicData.quantities')} PCS</div>
								<div>Boxes: {getDetail('basicData.cartons')}</div>
								<div>Weights: {''} KG</div>
							</TableCol>
							<TableCol
								class="invoice__table__border invoice__table__item font-bold text-right"
								span={6}
							>
								<span>Amount:</span>
								<br />
								<span>Shipping Fee:</span>
							</TableCol>
							<TableCol class="invoice__table__border invoice__table__item" span={6}>
								<div>
									{sign}
									{$detail.basicData?.itemAmount}
								</div>
								<div>
									{sign}{' '}
									<span class="outline-none" contenteditable on:blur={(e) => onChangeShipping(e)}>
										{getDetail('basicData.shipping')}
									</span>
								</div>
							</TableCol>
						</TableRow>
						<TableRow class="invoice__table__brother">
							<TableCol class="invoice__table__border invoice__table__item font-bold" span={12}
							></TableCol>
							<TableCol
								class="invoice__table__border invoice__table__item font-bold text-right"
								span={6}
							>
								Sub Total:
							</TableCol>
							<TableCol class="invoice__table__border invoice__table__item font-bold" span={6}>
								<div>
									<!-- {sign.value}{' '} -->
									{(
										($detail.basicData
											? Number(transformDisplayToNumber($detail.basicData.itemAmount))
											: 0) + Number($detail.basicData ? $detail.basicData.shipping : 0)
									).toFixed(2)}
								</div>
							</TableCol>
						</TableRow>
						<TableRow class="mt-15px">
							<div class="grid-col-span-24 font-size-14px">
								{@html getDetail('basicData.invoiceTips')}
							</div>
						</TableRow>
					</div>
				</div>
			</div>
		</PageLoading>
	</div>
</div>

<style></style>
